<template>
	<!-- <view class="" v-if="stockData['f43']"> -->
	<view class="">
		<tui-dropdown-list :show="dropdownShow" :top="94" :height="800" isMask @cancle="closeDropdown" >
			<template v-slot:selectionbox>
				<view class="cell" @click="showDrop">
					<view class="label">代码</view>
					<view class="flex align-center">
						<text>{{stockData?.['f58']}}</text>
						<text>[{{stockData?.['f57']}}]</text>
					</view>
				</view>
			</template>
			<template v-slot:dropdownbox>
				<view class="padding bg-white" >
					<tui-searchbar placeholder="股票代码" @search="getPositions" @input="inputKeyword" :value="keyword" :focus="focus"></tui-searchbar>
					<view class="text-df text-bold padding-bottom">请选择卖出仓位</view>
					<view class="flex justify-between text-gray">
						<view>手数</view>
						<view>市值</view>
						<view>买入价</view>
					</view>
					<scroll-view scroll-y="true" style="height:455rpx;" v-if="list.length">
						<view @click="select(index)" :class="currentIndex==index?'text-orange':''" class="flex justify-between align-center border-bottom padding-tb-sm" v-for="(item,index) in list" :key="index">
							<view>{{item.number/100}}</view>
							<view class="">{{item.cityValue}}</view>
							<view class="">{{item.buyprice}}</view>
						</view>
					</scroll-view>
					<view class="padding" v-else>
						<tui-no-data  :fixed="false" imgUrl="/static/images/nodata.png" :imgWidth="179*2" :imgHeight="126*2">
							<text class="text-sm text-gray">当前关键词无可用持仓</text>
						</tui-no-data>
					</view>
				</view>
			</template>
		</tui-dropdown-list>
		<view class="cell">
			<view class="label">买入价</view>
			<view class="text-orange">
				{{buyprice || '--'}}
			</view>
		</view>
		<view class="cell">
			<view class="label">现价</view>
			<view class="text-orange">
				{{ stockData?.['f43']/100 || ( returnBuyPrice || '--')}}
			</view>
		</view>
		<!-- 开启委托可改卖出价格 -->
		<view class="cell" v-if="sysConfigObj?.is_weituo==1">
			<view class="label">卖出价格</view>
			<view class="text-orange">
				<input type="text" class="text-nomal" v-model="price" placeholder="请输入卖出价格" />
			</view>
		</view>
		<view class="cell">
			<view class="label">持仓手数</view>
			<view class="">{{quancang}}</view>
		</view>
		<view class="cell">
			<view class="label">仓位</view>
			<view class="flex flex-wrap" style="align-items: center;">
				<text style="font-size: 24rpx;"  @click="chooseNum(item.num,'turnover')"  class="tag" :class="turnover==item.num?'active':''" v-for="(item,index) in turnovers" :key="index">{{item.name}}</text>
			</view>
		</view>
		<view class="cell">
			<view class="label">卖出手数</view>
			<input type="number" @blur="verifyHands" v-model="handNum" class="text-nomal" placeholder="输入卖出手数" />
		</view>
		<view class="cell">
			<view class="label" >总额(元)</view>
			<view >{{payTotal||'0'}}</view>
		</view>
		<view class="padding-sm pos-b">
			<tui-button :loading="submiting" @click="confirmSell" :disabled="current==null || handNum ==0 || submiting" type="theme">确认卖出</tui-button>
		</view>
	</view>
</template>

<script setup>
import {ref, inject, watch, computed, onMounted, nextTick} from 'vue';
import {onShow} from '@dcloudio/uni-app';

import {sellStock} from '@/api/index.js';
import {getMarketCode, getShortCode,getAllCode, getDotCode,manyAccMul} from '@/utils/stock.js';
import {mrSellLst} from '@/api/user.js';

const tui = inject('tui');

const props = defineProps({
	stockData: {
		type: Object,
		default: () => {}
	},
	code:{
		type: String,
		default: ''
	},
	i:{
		type:Number,
		default: 0
	}
});

const emits = defineEmits(['confirm', 'changeCode']);

const keyword = ref('');
const dropdownShow = ref(false);
const handNum = ref(0);
const turnover = ref(1);
const turnovers = ref([
	{name:'1/4',num:0.25},
	{name:'1/3',num:0.33},
	{name:'1/2',num:0.5},
	{name:'全仓',num:1},
]);
const list = ref([]);
const current = ref(null);
const currentIndex = ref(0);
const quancang = ref(0);
const buyprice = ref(0);
const price = ref('');
const focus = ref(false);
const submiting = ref(false);
const returnBuyPrice = ref(0);
const sysConfigObj = ref({});

onShow(() => {
	if (uni.getStorageSync('sysConfig')) {
		sysConfigObj.value = uni.getStorageSync('sysConfig');
	}
});

watch(() => handNum.value, (newValue, oldValue) => {
	let ratio= (newValue/quancang.value).toFixed(2);
	let happen = turnovers.value.find(v=>v.num==ratio);
	if(happen){
		turnover.value = happen.num
	}else{
		turnover.value = 0
	}
});

const actualPrice = computed(() => {
	let currPrice = props.stockData?.['f43']/100 || (returnBuyPrice.value || 0);
	return currPrice;
});

const marketCode = computed(() => {
	return getMarketCode(props.code)
});

const payTotal = computed(() => {
	return manyAccMul(handNum.value?handNum.value:0,actualPrice.value,100)
});

onMounted(() => {
	keyword.value = getShortCode(props.code)
	getPositions();
	setTimeout(()=>{
		price.value = props.stockData?.['f43']/100||'--'
	},500)
}) 

const confirmSell = () => {
	if(handNum.value==0||handNum.value==''){
		tui.toast('请输入正确的手数')
		return
	}
	emits('confirm',{
		title:props.stockData['f58'],
		price:actualPrice.value,
		number:handNum.value*100,
		total:payTotal.value,
		method:'sell'
	})
}

const inputKeyword = (keywordV) => {
	keyword.value = keywordV.value
}

const verifyHands = () => {//验证手数
	turnover.value = 0
	if(handNum.value>quancang.value){//如果手数大于最大仓位手数
		handNum.value = quancang.value
	}
}

const closeDropdown = () => {
	focus.value = false;
	dropdownShow.value = false;
}

const showDrop = () => {
	dropdownShow.value = !dropdownShow.value;
	nextTick(()=>{
		focus.value = true;
	})
}

const sell = () => {
	if(handNum.value==0||handNum.value==''){
		tui.toast('请输入正确的手数')
		return
	}
	submiting.value = true
	let postData={
		id:current.value.id,
		allcode:getAllCode(props.code),
		canBuy:handNum.value,
		waystatus:1,
		sellprice:actualPrice.value
	}
	sellStock(postData).then(res=>{
		tui.modal(null,res.msg,false,()=>{
			submiting.value = false
			if(res.code == 1){
				uni.redirectTo({
					url:sysConfigObj.value.is_weituo==1?'/pages/ucenter/entrust':'/pages/ucenter/holding'
				})
			}
		})
	})
}

const cacleHandNum = () => {
	current.value = list.value[currentIndex.value];
	returnBuyPrice.value = current.value.return_sell_price
	quancang.value = current.value.canBuy;
	buyprice.value = current.value.buyprice
	let handNumV = parseInt(turnover.value*quancang.value);//全仓*仓位取整小于0 ，仓位置为1
	if(handNumV<0){
		turnover.value =1
	}
	handNum.value = parseInt(turnover.value*quancang.value);
	//如果切换了股票代码，通知外层重新建立新的长连接
	if(props.code != getDotCode(current.value.allcode)){
		emits('changeCode',getDotCode(current.value.allcode))
	}
}

const select = (i) => {
	currentIndex.value = i;
	cacleHandNum();
	dropdownShow.value= false
}

const getPositions = () => {
	currentIndex.value = 0;
	mrSellLst({
		keyword:keyword.value
	}).then(res=>{
		if(res.data.length){
			list.value = res.data;
			cacleHandNum()
		}else{
			if(this.i==1) tui.toast('暂无持仓数据');
		}
	})
}

const chooseNum = (val,type) => {
	let handNumV = parseInt(val*quancang.value);
	if(handNumV!=0){
		turnover.value=val;
		handNum.value = handNumV
	}else{
		tui.toast(`当前最大仓位${quancang.value}手，无法选择更小仓位`)
	}
}

defineExpose({sell});
</script>
<style lang="scss" scoped>
	// @import 'common.scss';
	
	.boxshow{
			box-shadow: 0 0rpx 16rpx rgba(0, 0, 0, 0.14);
			border-radius: 16rpx;background: #fff;
		}
		.cell{
			@extend .boxshow;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;margin:16rpx 20rpx;font-size: 26rpx;
	    .sign{width: 36rpx;height: 24rpx;margin-right: 6rpx;}
			.label{
				width: 140rpx;
				color: #000000;
				font-size: 32rpx;
				font-weight: 400;
				font-family: PingFangSC, PingFang SC;
			}
			
			.tag{
				font-size: 20rpx;
				padding: 4rpx 20rpx;background: #f5f4f6;border-radius: 4rpx;
				margin: 10rpx 10rpx;
				&.active{
					background: #fff0ea;color:#ff5f25;
				}
			}
		}
		.pos-b{
			position: fixed;left: 0;box-sizing: border-box;
			width: 100%;bottom: 0; z-index: 99;
		}
	
	.name,.price,.up-down{
		box-sizing: border-box;
		padding: 16rpx;font-size: 26rpx
	}
	.name{width: 25%;}
	.price{width: 24%;text-align: center;}
	.up-down{width: 25%;text-align: right;}
	.cell {
		box-shadow: none !important;
		border-radius: 0 !important;
		border-bottom: 1px solid #e8e8e8 !important;
		background: #fff !important;
	}
</style>s